<template>
	<div class="ctfQuestion-warp">
	    <Row style="margin-bottom:10px">
        	<Col span="3">
        		<!--<Button type="primary" icon="md-add" @click="addTag"></Button>-->
        	</Col>
    	</Row>
    	<Form :label-width="100" :model="formValidate" ref="formValidate">
    		<!--<Row style="text-align:center">
    			<Col span="8">内容</Col>
    			<Col span="8">时间</Col>
    			<Col span="6">操作</Col>
    		</Row>-->
    		<!--<Divider />-->
    		<div v-for="(item, index) in formValidate.tagList" :key="index">
    		<Row>
	            <Col span="24">
			        <FormItem
		                label="提示内容："
		                :prop="'tagList.' + index + '.info'"
		                :rules="{required: item.edit, message: '不能为空', trigger: 'change'}">
	                    <Input type="textarea" :maxlength="200" v-model.trim="item.info" placeholder="请输入提示内容" v-if="item.edit"></Input>
	                    <span v-if="!item.edit" style="word-break:break-all;margin-top:10px;">{{item.info}}</span>
			        </FormItem>
			    </Col>
			</Row>
		    <Row>
		    	<Col span = "12">
		    		<Row>
					    <Col span="7">
					    	<FormItem label="定时显示：">
					    		<Checkbox v-model="item.timer" @on-change="setTime(item)" style="line-height:32px;" :disabled="!item.edit"></Checkbox>
			               </FormItem>
			            </Col>
		                <Col span="14">
		                	<FormItem label="显示时间：">
			                	<DatePicker v-model="item.time" 
				                    	placeholder="请选择时间" 
				                    	:value="item.time"
				                    	type="datetime"
				                    	style="width: 200px" 
				                    	:editable="false"
				                    	format="yyyy-MM-dd HH:mm"
				                    	v-if="item.edit && item.timer"
				                    	@on-change="changeTime($event,item)"
				                ></DatePicker>
				                <!--:options = "timeOptions"-->
				                <span v-if="!item.edit" style="line-height:32px;">{{showTimeNotSecond(item.promptTime)}}</span>
			                </FormItem>
		                </Col>
	                </Row>
                </Col>
                <Col span="5" offset="1" class="btn-group">
					<template v-if="item.infoVisibility == 0">
						<Button type="info" @click="checkQuestionSolve(item)" size="small">显示</Button>
					</template>
					<template v-else>
						<Button @click="changeTagVisible(item)" size="small" type="error">
							<span>隐藏</span>
						</Button>
					</template>
                	<Button @click="saveCtfTargetTags(item, true)" v-if="item.edit" size="small" type="primary">确定</Button>
                	<Button @click="item.edit = true" v-if="!item.edit" size="small" type="primary">修改</Button>
                    <Button @click="removeTag(index)" v-if="!item.id" size="small" type="error">删除</Button> 
                    <Button @click="delCtfTargetTags(item.id)" v-if="item.id" size="small" type="error">删除</Button>
                </Col>
                <!--<Divider dashed />-->
            </Row>
            <Divider dashed style="margin-top:0px;"/>
            </div>
	        <FormItem>
	            <Row>
	                <Col span="12">
	                    <Button type="primary" ghost long @click="addTag" icon="md-add" :disabled="formValidate.tagList.some(item => !item.id)">添加</Button>
	                </Col>
	            </Row>
	        </FormItem>
	    </Form>
		<Modal
				v-model="showModal"
				width="300"
				@on-ok="changeTagVisible(currentItem)">
			<p slot="header" style="color:#f60">
				<Icon type="ios-information-circle-outline"></Icon>
				<span>请确认</span>
			</p>
			<div>已有团队正确提交，是否继续放出提示</div>
		</Modal>
	</div>
</template>
<script>
	import {createCtfTargetTags,modifyCtfTargetTags,delCtfTargetTags,queryCtfTargetTags,clearCtfTargetTags,changeTagVisible} from '@/api/drill_compete'
	import { getQuestionSolveStatic } from '@/api/compitionStatic'
	import { format, showTimeNotSecond } from '@/libs/utils'
	export default {
		props:['target','sceneInfo'],
		data(){
			return{
				showTimeNotSecond,
				showModal: false,
				currentItem: null,
				index:0,
				tagList:[],
				totalCount:0,
				tag:{},
				tagModal:{
					show:false,
					loading:true,
					title:'添加Tag'
				},
				tagInfo:{tagList:[]},
				formValidate:{
//					chaId: this.chaId,
//					tag: "",
					tagList:[]
				},
				ruleValidate:{
					info:[
					   { required: true, message: '提示内容不能为空', trigger: 'change' }
					]
				},
				tagCol:[
					{
						title: '名称',
						key: 'info',
//						align: 'center',
						ellipsis: true,
						tooltip:true,
						render:(h,params) => {
							if(params.row.edit){
								return h('Input',{
									props:{
										value:params.row.value,
										type:'textarea',
										maxlength:200,
										autosize:"{minRows: 2,maxRows: 5}"
									}
								})
							}else{
								return h('span',params.row.tag)
							}
						}
					},
//					{
//						title: 'createTime',
//						key: 'createTime',
//						align: 'center',
//						ellipsis: true,
//						tooltip:true
//					},
					{
					    title:'操作',
					    width:140,
					    render:(h,params) => {
					    	return h('div', [
					    	    h('Button', {
									props: {
										type: 'primary',
										size: 'small'
									},
									style: {
										marginRight: '5px'
									},
									on: {
										click: () => {
//											this.tagModal.show = true;
//											this.tagModal.title = '修改tag';
//											this.getCtfTargetTagsInfo(params.row);
//											params.row.edit = true;
											this.saveCtfTargetTags(params.row);
										}
									}
								}, '确定'),
								h('Button', {
									props: {
										type: 'primary',
										size: 'small'
									},
									style: {
										marginRight: '5px'
									},
									on: {
										click: () => {
//											this.tagModal.show = true;
//											this.tagModal.title = '修改tag';
//											this.getCtfTargetTagsInfo(params.row);
											params.row.edit = true;
										}
									}
								}, '修改'),
								h('Poptip', {
									props: {
										confirm: true,
										'ok-text': "确定",
										'cancel-text': "取消",
										type: 'error',
										size: 'large',
										title: '你确定要删除吗?',
										transfer:true
									},
									style: {
										marginLeft: '0px'
									},
									on: {
										'on-ok': () => {
											this.delCtfTargetTags(params.row.tagId)
										}
									}
								}, [
									h('Button', {
										props: {
											type: 'error',
											size: 'small'
										},
										style: {
											marginRight: '5px'
										},
									}, '删除')
								])
							])
					    }
					},
				],
				timeOptions: {
                },
                startDate:new Date()
      		}
		},
		computed:{

		},
		filters:{

		},
		watch:{
//			'chaId':function(id){
//				this.formValidate.chaId = id;
//			},
//			'show':function(id){
//				this.queryCtfTargetTags();
//			}	
//			'sceneInfo':{
//				handler:function(val){
//					let _this = this;
//					_this.startDate = val.startTime;
//					_this.timeOptions = {
//						disabledDate (date) {
//		                	let start = val.startTime;
//		                	let end = val.endTime;
//		                    return date && (date.valueOf() > end || date.valueOf() < start);
//		                }
//					}
//				},
//				deep:true
//			}
		},
		mounted(){
			this.startDate = this.sceneInfo.startTime;
			let _this = this;
			this.timeOptions = {
				disabledDate (date) {
                	let start = _this.sceneInfo.startTime;
                	let end = _this.sceneInfo.endTime;
                    return date && (date.valueOf() > new Date(end).getTime() || date.valueOf() < new Date(start).getTime());
                }
			}
			this.queryCtfTargetTags();
		},
		created(){

		},
		methods:{
			addTag(){
				this.index ++ ;
				this.tagList.push({
					info:'',
					index:this.index,
					infoVisibility:0,
					questionId: this.target.questionId,
					sceneId:this.$route.query.id,
					targetId:this.target.id,
//					promptTime:this.startDate,
					promptTime:this.startDate,
					time:this.startDate,
					timer:false,
					type:0,
					edit:true
				})
			},
			removeTag(index){
				this.tagList.splice(this.tagList.findIndex(tag => tag.index === index), 1)
			},
			queryCtfTargetTags(){
				let params = {
					sceneId:this.$route.query.id,
					questionId:this.target.questionId,
					targetId:this.target.id,
					pageIndex:1,
					pageSize:10000
				}
				queryCtfTargetTags(params).then(data => {
					if(data.code == 1){
						this.tagList = data.data.items || data.data;
						this.formValidate.tagList = data.data.items || data.data;
						this.tagList.forEach(tag => {
							this.$set(tag,'edit',false);
							if(tag.promptTime){
								this.$set(tag,'timer',true);
								this.$set(tag,'time',tag.promptTime);
							}
						})
						if(data.data.items){
							this.index = data.data.items.length;
						}
					}else{
						this.$Message.warning(data.message);
					}
				})
			},
			delCtfTargetTags(id){
				delCtfTargetTags(id).then(data => {
					if(data.code == 1){
						this.$Message.info('操作成功');
						this.queryCtfTargetTags();
					}else{
						this.$Message.warning(data.message);
					}
				})
			},
			modifyCtfTargetTags(){
				if(this.tag.info == ''){
					this.$Message.warning('提示内容不能为空');
					return
				}
				if(this.tag.timer == false){
					this.tag.promptTime = '';
				}
				modifyCtfTargetTags(this.tag).then(data => {
//					this.cancelLoading('tagModal');
					if(data.code == 1){
						this.$Message.info('操作成功');
//						this.tagModal.show = false;
//						let boardCast = {
//							chaId:this.chaId,
//							op:"修改",
//							type:"提示",
//							name:this.tag.tag
//						}
//						this.$emit('addBoardCast', boardCast)
						this.queryCtfTargetTags();
					}else{
						this.$Message.warning(data.message);
					}
				})
			},
			createCtfTargetTags(){
				if(this.tag.info == ''){
					this.$Message.warning('提示内容不能为空');
					return
				}
				if(this.tag.timer == false){
					this.tag.promptTime = '';
				}
				createCtfTargetTags(this.tag).then(data => {
//					this.cancelLoading('tagModal');
					if(data.code == 1){
						this.$Message.info('操作成功');
//						this.tagModal.show = false;
						this.queryCtfTargetTags();
//						let boardCast = {
//							chaId:this.chaId,
//							op:"添加",
//							type:"提示",
//							name:this.tag.tag
//						}
//						this.$emit('addBoardCast', boardCast)
					}else{
						this.$Message.warning(data.message);
					}
				})
			},
			// 判断传入的时间字符串是否在当前时间之前
			isBeforeTimestamp(dataStr) {
				return new Date(dataStr) <= new Date()
			},
			saveCtfTargetTags(tag, noValidation){
				if (this.isBeforeTimestamp(tag.promptTime) && !noValidation) { // 隐藏、展示操作不需要验证时间
					this.$Message.warning('显示时间不得早于当前时间')
					return
				}
				this.tag = tag;
//				this.$refs['formValidate'].validate((valid) => {
//          		if (valid) {
            			if(!tag.id){
            				this.createCtfTargetTags();
            			}else{
            				this.modifyCtfTargetTags()
            			}
//          		}else{
//          			this.cancelLoading('ctfModal');
//          		}
//          	})
			},
			getCtfTargetTagsInfo(data){
				this.formValidate = JSON.parse(JSON.stringify(data));
			},
			changePage(page){
				this.queryCtfInfo.page = page;
				this.queryCtfList();
			},
			changeSize(size){
				this.queryCtfInfo.rows = size;
				this.queryCtfList();
			},
			cancelLoading(name){
		    	this[name].loading = false;
		      	setTimeout(() => {
		      		this[name].loading = true;
		      	})
		    },
		    cancel(name){
		  		this.$refs[name].resetFields();
		  	},
		  	changeTagVisible(item){
				let params = JSON.parse(JSON.stringify(item));
				params.infoVisibility = params.infoVisibility == 0 ? 1 : 0;
				this.saveCtfTargetTags(params, true);
//		  		changeTagVisible(item.id,status).then(data => {
//		  			if(data.code == 1){
//		  				this.queryCtfTargetTags();
//		  			}else{
//		  				this.$Message.warning(data.message);
//		  			}
//		  		})
		  	},
			// 查询题目解决情况
			checkQuestionSolve(item) {
				getQuestionSolveStatic({
					pageIndex: 1,
					pageSize: 10,
					sceneId: this.$route.query.id,
					questionId: item.questionId,
					finishStatus: 1
				}).then(({ code, data, message }) => {
					if (code === 1) {
						if (data.total) { // 有团队已经解答出题目，需要给出提示
							this.currentItem = item
							this.showModal = true
						} else {
							this.changeTagVisible(item)
						}
					} else {
						this.$Message.warning(message)
					}
				}).catch(() => {
					this.$Message.error('获取题目解答详情异常');
				})
			},
			changeTime(time,item){
				if (this.isBeforeTimestamp(time)) {
					this.$Message.warning('显示时间不得早于当前时间')
				}
				item.promptTime = time+':00';
			},
			// 默认十分钟后放出提示
			setTime(item){
				let timeStr = format(new Date(new Date().getTime() + 600000))
				item.time = timeStr;
				item.promptTime = timeStr;
			}
		}
	}
</script>

<style scoped>
.btn-group {
	height: 32px;
	display: flex;
	align-items: center;
}
.btn-group > button {
	margin-right: 6px;
}
.btn-group > button:last-child {
	margin-right: 0;
}
</style>